import Vue from 'vue'
import store from '@/store' // 引入 Vuex 以获取 userId

const state = {
	websocket: null,
	userId: null,
};

const mutations = {
	SET_USER_ID(state, userId) {
		state.userId = userId;
	},
	INIT_WEBSOCKET(state) {
		if (state.websocket || !state.userId) return; // 防止重复初始化，确保 userId 存在

		state.websocket = new WebSocket(`ws://127.0.0.1:5109/websocket/${state.userId}`);

		state.websocket.onopen = () => {
			console.log(`WebSocket 连接成功: 用户ID ${state.userId}`);
		};

		state.websocket.onmessage = (event) => {
			console.log('收到服务器消息:', event.data);
			uni.showModal({
				title: '新消息',
				content: event.data,
				showCancel: false
			});
		};

		state.websocket.onerror = () => {
			console.error("WebSocket 连接发生错误");
		};

		state.websocket.onclose = () => {
			console.log("WebSocket 连接已关闭");
		};
	},
	CLOSE_WEBSOCKET(state) {
		if (state.websocket) {
			state.websocket.close();
			state.websocket = null;
			state.userId = null
		}
	}
};

const actions = {
	initWebSocket({
		commit
	}, userId) {
		if (userId) {
			commit('SET_USER_ID', userId);
			commit('INIT_WEBSOCKET');
		} else {
			console.warn("WebSocket 连接失败：userId 为空");
		}
	},
	closeWebSocket({
		commit
	}) {
		commit('CLOSE_WEBSOCKET');
	}
};

export default {
	namespaced: true,
	state,
	mutations,
	actions,
};